<template>
  <el-form>
    <el-upload
      class="avatar-uploader"
      :action="uploadUrl"
      :headers="headers"
      :limit="1"
      ref="upload"
      :on-remove="imageListRemove"
      :on-change="handleChange"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :auto-upload="false"
    >
      <el-button size="small" round type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传固定的xls/xlsx文件。您可以点击<a style="color: #3a8ee6;" :href="src">下载模板</a></div>
    </el-upload>
    <el-form-item align="right">
      <el-button size="small" round type="primary" @click="onCancel" style="margin-top: 20px;">取消</el-button>
      <el-button size="small" round type="primary" @click="onSubmit" style="margin-top: 20px;">确认</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import { getToken,uploadUrl} from '@/utils/auth'

  export default {
    name: 'index',
    props: {
      src: { type: String, default: '' },
      default: { type: Boolean, default: false }
    },
    components: {
    },
    data() {
      return {
        headers: { 'x-auth-token': getToken() },
        uploadUrl: uploadUrl,
        imageUrl: '',
        fileList: [],
        dataList: [],
        form: {
          image: ''
        },
        show: {
          barCode: '',
          name: '',
          brandId: '',
          goldQualityId: '',
          serialNumber: '',
          originalSerialNumber: '',
          certificateNumber: '',
          innerStyleNumber: '',
          factoryStyleNumber: '',
          jewelryKind: '',
          styleId: '',
          tagSize: '',
          jewelryCategory: '',
          netWeight: '',
          goldPrice: '',
          actualSize: '',
          totalWeight: '',
          purchaseTime: '',
          lossPercentage: '',
          salePropertyId: '',
          supplierId: '',
          note: '',
          salePrice: '',
          salePriceCost: '',
          purchaseCost: '',
          processingFee: '',
          certificateFee: '',
          boutiqueFee: '',
          saleFactor: '',
          mainStone: {
            id: '',
            name: '',
            shape: '',
            cutting: '',
            stoneNumber: '',
            pricingMethodId: '',
            unitPrice: 0,
            color: '',
            clarity: '',
            weight: 0,
            grain: ''
          },
          subStones: []
        }
      }
    },
    async created() {
    },
    methods: {
      onSubmit() {
        // 输出
        this.$emit('operate', this.dataList)
      },
      onCancel() {
        this.$emit('cancel')
      },
      imageListRemove(file, fileList) {
        this.fileList.splice(0, 1)
        this.dataList = []
      },
      handleExceed(files, fileList){
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      handleChange(file, fileList) {
        this.fileTemp = file.raw
        if (this.fileTemp) {
          if ((this.fileTemp.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            || (this.fileTemp.type === 'application/vnd.ms-excel')) {
            this.importfxx(this.fileTemp)
          } else {
            this.$message({
              type: 'warning',
              message: '附件格式错误，请删除后重新上传！'
            })
          }
        } else {
          this.$message({
            type: 'warning',
            message: '请上传附件！'
          })
        }
      },
      importfxx(obj) {
        let _this = this
        let inputDOM = this.$refs.inputer
        // 通过DOM取文件数据
        this.file = event.currentTarget.files[0]
        var rABS = false // 是否将文件读取为二进制字符串
        var f = this.file
        var reader = new FileReader()
        // if (!FileReader.prototype.readAsBinaryString) {
        FileReader.prototype.readAsBinaryString = function(f) {
          var binary = ''
          var rABS = false // 是否将文件读取为二进制字符串
          var pt = this
          var wb // 读取完成的数据
          var outdata;
          var reader = new FileReader()

          reader.onload = function(e) {
            var bytes = new Uint8Array(reader.result)
            var length = bytes.byteLength
            for (var i = 0; i < length; i++) {
              binary += String.fromCharCode(bytes[i])
            }
            var XLSX = require('xlsx')
            if(rABS) {
              wb = XLSX.read(btoa(fixdata(binary)), { // 手动转化
                type: 'base64'
              })
            } else {
              wb = XLSX.read(binary, {
                type: 'binary'
              })
            }
            outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])// outdata就是你想要的东西
            this.da = [...outdata]
            if (_this.default) {
              _this.dataList = outdata
            } else {
              _this.importForm(outdata)
            }
          }
          reader.readAsArrayBuffer(f)
        }
        if (rABS) {
          reader.readAsArrayBuffer(f)
        } else {
          reader.readAsBinaryString(f)
        }
      },
      importForm(outdata) {
        this.dataList = []
        var isTrue = true
        outdata.forEach((value, index, arr) => {
          if (value['条码号'] == null || value['条码号'] == 'undefined') {
            this.$message({
              message: '第' + (index + 2) + '行，条码号不能为空，请删除后重新上传！',
              type: 'error'
            })
            isTrue = false
          }
        })
        if (isTrue) {
          outdata.forEach((value, index, arr) => {
            var show = {};
            const barcode = value['条码号'].substring(0, 16);
            show.id = barcode;
            show.barCode = barcode;
            show.name = value['首饰名称']
            show.stateText = ''
            show.brand = value['首饰品牌']
            show.brandId = ''
            show.goldQuality = value['金料成色']
            show.goldQualityId = ''
            show.serialNumber = value['芯片号']
            show.originalSerialNumber = value['原编号']
            show.certificateNumber = value['证书号']
            show.innerStyleNumber = value['内部款号']
            show.factoryStyleNumber = value['厂家款号']
            show.jewelryKind = value['首饰类别']
            show.jewelryKindId = ''
            show.style = value['款式系列']
            show.styleId = ''
            show.tagSize = value['标签手寸']
            show.jewelryCategory = value['首饰大类']
            show.jewelryCategoryId = ''
            show.netWeight = value['净金重(g)']
            show.goldPrice = this.moneyDelete(value['金价'])
            show.actualSize = value['实际手寸']
            show.totalWeight = value['总件重(g)']
            show.purchaseTime = value['进货时间']
            show.lossPercentage = value['金耗%']
            show.salePropertyId = value['销售属性']
            show.supplierId = value['供应商']
            show.goldContent = value['含金量']
            show.note = value['首饰备注']
            show.salePrice = this.moneyDelete(value['售价'])
            show.salePriceCost = this.moneyDelete(value['售价成本'])
            show.purchaseCost = this.moneyDelete(value['进货成本'])
            show.processingFee = this.moneyDelete(value['加工费'])
            show.certificateFee = this.moneyDelete(value['证书费'])
            show.boutiqueFee = this.moneyDelete(value['精品费单价'])
            show.saleFactor = value['销售倍率']
            show.mainStone = {}
            show.mainStone.id = ''
            show.mainStone.name = value['主石名称']
            show.mainStone.shape = value['主石形状']
            show.mainStone.cutting = value['主石切工']
            show.mainStone.stoneNumber = value['主石石号']
            show.mainStone.pricingMethodId = this.moneyDelete(value['主石计价'])
            show.mainStone.unitPrice = this.moneyDelete(value['主石单价'])
            show.mainStone.color = value['主石颜色']
            show.mainStone.clarity = value['主石净度']
            show.mainStone.weight = value['主石重(ct/g)']
            show.mainStone.grain = value['主石粒数']
            show.subStones = []
            show.subStones.push({
              name: value['副石名称1'],
              pricingMethodId: value['副石计价1'],
              stoneNumber: value['副石石号1'],
              spec: value['副石规格1'],
              weight: this.moneyDelete(value['副石石重(ct/g)1']),
              grain: value['副石粒数1'],
              unitPrice: this.moneyDelete(value['副石单价1']),
              forehead: value['宝石额1']
            })
            show.subStones.push({
              name: value['副石名称2'],
              pricingMethodId: value['副石计价2'],
              stoneNumber: value['副石石号2'],
              spec: value['副石规格2'],
              weight: this.moneyDelete(value['副石石重(ct/g)2']),
              grain: value['副石粒数2'],
              unitPrice: this.moneyDelete(value['副石单价2']),
              forehead: value['宝石额2']
            })
            show.subStones.push({
              name: value['副石名称3'],
              pricingMethodId: value['副石计价3'],
              stoneNumber: value['副石石号3'],
              spec: value['副石规格3'],
              weight: this.moneyDelete(value['副石石重(ct/g)3']),
              grain: value['副石粒数3'],
              unitPrice: this.moneyDelete(value['副石单价3']),
              forehead: value['宝石额3']
            })
            show.subStones.push({
              name: value['副石名称4'],
              pricingMethodId: value['副石计价4'],
              stoneNumber: value['副石石号4'],
              spec: value['副石规格4'],
              weight: this.moneyDelete(value['副石石重(ct/g)4']),
              grain: value['副石粒数4'],
              unitPrice: this.moneyDelete(value['副石单价4']),
              forehead: value['宝石额4']
            })
            show.subStones.push({
              name: value['副石名称5'],
              pricingMethodId: value['副石计价5'],
              stoneNumber: value['副石石号5'],
              spec: value['副石规格5'],
              weight: this.moneyDelete(value['副石石重(ct/g)5']),
              grain: value['副石粒数5'],
              unitPrice: this.moneyDelete(value['副石单价5']),
              forehead: value['宝石额5']
            })
            // 数据字典翻译
            this.translateDicts('brand', show.brand).then(brand => {
              show.brandId = brand
              if (show.brandId === '') {
                show.brand = ''
              }
            })
            this.translateDicts('jewelryKind', show.jewelryKind).then(jewelryKind => {
              show.jewelryKindId = jewelryKind
              if (show.jewelryKindId === '') {
                show.jewelryKind = ''
              }
            })
            this.translateDicts('goldQuality', show.goldQuality).then(goldQuality => {
              show.goldQualityId = goldQuality
              if (show.goldQualityId === '') {
                show.goldQuality = ''
              }
            })
            this.translateDicts('style', show.style).then(style => {
              show.styleId = style
              if (show.styleId === '') {
                show.style = ''
              }
            })
            this.translateDicts('jewelryCategory', show.jewelryCategory).then(jewelryCategory => {
              show.jewelryCategoryId = jewelryCategory
              if (show.jewelryCategoryId === '') {
                show.jewelryCategory = ''
              }
            })
            this.translateDicts('saleProperty', show.salePropertyId).then(saleProperty => {
              show.salePropertyId = saleProperty
            })
            this.translateDicts('supplierList', show.supplierId).then(supplierList => {
              show.supplierId = supplierList
            })
            this.translateDicts('mainStone', show.mainStone.name).then(mainStone => {
              show.mainStone.id = mainStone
              show.mainStone.name = mainStone
            })
            this.translateDicts('pricingMethod', show.mainStone.pricingMethodId).then(pricingMethod => {
              show.mainStone.pricingMethodId = pricingMethod
            })
            show.subStones.forEach(item => {
              this.translateDicts('pricingMethod', item.pricingMethodId).then(pricingMethod => {
                item.pricingMethodId = pricingMethod
              })
            })
            this.dataList.push(show)
          })
          this.$message({
            message: '请耐心等待导入成功',
            type: 'success'
          })
        }
      },
      async translateDicts(type, value) {
        var data = ''
        var dataList = this.jewelryList[type]
        dataList.forEach(item => {
          if (item.value === value) {
            data = item.id
          }
        })
        return data
      },
      moneyDelete(num) {
        if (num && num != undefined && num != null) {
          let _num = num
          _num = _num.toString()
          _num = _num.replace(/,/gi, '')
          _num = _num.replace(/[^\d.]/g, '')
          return _num
        } else {
          return num
        }
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .box-card {
    width: 480px;
  }
</style>
